import imghdr
from rest_framework.serializers import ModelSerializer, SlugRelatedField
from rest_framework import serializers
from .models import UserAccount, Blog, Tag
import base64


class Base64BinaryField(serializers.Field):
    def to_representation(self, value):
        # 数据库bytes转base64字符串
        img_type = imghdr.what(None, value)
        if img_type is None:
            img_type = "jpeg"
        if value:
            return f"data:image/{img_type};base64," + base64.b64encode(value).decode()
        return ""

    def to_internal_value(self, data):
        # base64字符串转bytes
        if isinstance(data, str) and data.startswith("data:image"):
            try:
                header, b64data = data.split(";base64,")
                return base64.b64decode(b64data)
            except Exception:
                raise serializers.ValidationError("图片base64格式错误")
        elif isinstance(data, bytes):
            return data
        return b""


class UserProfileSerializer(ModelSerializer):
    class Meta:
        model = UserAccount
        fields = (
            "id",
            "name", 
            "tag_line",
            "birthday",
            "permission",
            "avator",
            "view_nums",
            "otherInfos",
        )
        read_only_fields = ("id", "permission")


class TagSerializer(ModelSerializer):
    class Meta:
        model = Tag
        fields = "__all__"


class BlogSerializerHomePage(ModelSerializer):
    labels = SlugRelatedField(
        many=True, slug_field="name", queryset=Tag.objects.all(), required=False
    )
    blog_cover = Base64BinaryField(required=False)

    class Meta:
        model = Blog
        fields = (
            "id",
            "author",
            "title",
            "desc",
            "created_at",
            "updated_at",
            "blog_cover",
            "labels",
            "like_nums",
            "view_nums",
            "is_top",
        )


class BlogSerializerDetailPage(ModelSerializer):
    labels = SlugRelatedField(
        many=True, slug_field="name", queryset=Tag.objects.all(), required=False
    )
    blog_cover = Base64BinaryField(required=False)

    class Meta:
        model = Blog
        fields = "__all__"


class BlogSerializerAdd(ModelSerializer):
    labels = SlugRelatedField(
        many=True, slug_field="name", queryset=Tag.objects.all(), required=False
    )
    blog_cover = Base64BinaryField(required=False)

    class Meta:
        model = Blog
        fields = (
            "author",
            "title",
            "context",
            "toc",
            "desc",
            "created_at",
            "updated_at",
            "blog_cover",
            "labels",
            "is_top",
        )


class BlogSerializerTimeline(ModelSerializer):
    class Meta:
        model = Blog
        fields = ("id", "title", "created_at", "updated_at")


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=255)
    password = serializers.CharField(max_length=255, write_only=True)
